package com.wang.consumer;

import java.util.Arrays;
import java.util.Properties;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.apache.kafka.clients.consumer.ConsumerRecords;
import org.apache.kafka.clients.consumer.KafkaConsumer;

public class CustomConsumer {
	public static void main(String[] args) {
		// 创建消费者配置信息
		Properties properties = new Properties();
		// 指定连接的Kafka集群
		properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "hadoop114:9092");
		// 开启自动提交
		properties.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, true);
		// 自动提交的延时
		properties.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, "1000");
		// key的序列化类
		properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");
		// value的序列化类 
		properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, "org.apache.kafka.common.serialization.StringDeserializer");
		// 制定consumer group
		properties.put(ConsumerConfig.GROUP_ID_CONFIG, "bigdata");
		// 重置消费者的 offset
		properties.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");

		// 定义consumer 
		KafkaConsumer<String, String> consumer = new KafkaConsumer<>(properties);
		// 消费者订阅的topic, 可同时订阅多个
		consumer.subscribe(Arrays.asList("test"));

		while (true) {
			// 读取数据，读取超时时间为100ms
			ConsumerRecords<String, String> records = consumer.poll(100);

			for (ConsumerRecord<String, String> record : records) {
				System.out.printf("offset = %d, key = %s, value = %s%n", record.offset(), record.key(), record.value());
			}
		}
	}
}
